package org.folio.rest.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.rest.impl.other.PartyLogSave;
import org.folio.rest.impl.other.PartyUtil;
import org.folio.rest.jaxrs.model.ReaderReserveGroup;
import org.folio.rest.jaxrs.model.ReserveCollection;
import org.folio.rest.jaxrs.model.ReserveGroup;
import org.folio.rest.jaxrs.resource.PartyReserve;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.PostgresClient;
import org.folio.rest.persist.cql.CQLWrapper;
import org.folio.rest.tools.utils.ValidationHelper;

import javax.ws.rs.core.Response;
import java.util.*;
import java.util.stream.Collectors;

import static io.vertx.core.Future.succeededFuture;

/**
 * @author lee
 * @Classname PartyReserveImpl
 * @Description TODO
 * @Date 2020/6/18 16:42
 * @Created by lee
 */
public class ReserveImpl implements PartyReserve {
    private final Logger logger = LoggerFactory.getLogger("modparty");

    private static final String NOTIFY_TABLE = "reserve";

 
    @Override
    public void postPartyReserve(String lang, org.folio.rest.jaxrs.model.Reserve entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        List<ReaderReserveGroup> readerReserve = entity.getReaderReserveGroup();
        List<org.folio.rest.jaxrs.model.Reserve> reserves = new ArrayList<>();
        entity.setReaderReserveGroup(new ArrayList<>());
        entity.setIsDel(0);
        entity.setReserveDate(DateUtil.formatDateTime(new Date()));
        readerReserve.forEach(a->{
            org.folio.rest.jaxrs.model.Reserve  tmp = new org.folio.rest.jaxrs.model.Reserve();
            BeanUtil.copyProperties(entity,tmp);
            tmp.getReaderReserveGroup().add(a);
            tmp.setId(UUID.randomUUID().toString());
            reserves.add(tmp);
        });
        List<String> list = readerReserve.stream().map(a -> a.getBarcode()).collect(Collectors.toList());
        PostgresClient postgresClient = PgUtil.postgresClient(vertxContext, okapiHeaders);
        postgresClient.saveBatch(NOTIFY_TABLE,reserves,reply->{
            if (reply.succeeded())
            {

                asyncResultHandler.handle(succeededFuture(PostPartyReserveResponse.respond201WithApplicationJson(entity,PostPartyReserveResponse.headersFor201())));
                PartyLogSave.saveLog("新增活动名称为【"+ entity.getPartyName() +"】读者编号为【"+list.toString()+"】",2, entity.getMetadata(),entity.getOperator(),okapiHeaders,asyncResultHandler,postgresClient);
            }else {
                ValidationHelper.handleError(reply.cause(), asyncResultHandler);
            }
        });

    }


    @Override
    public void getPartyReserve(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
          CQLWrapper cql = null;
          if (!StrUtil.isBlankOrUndefined(query))
          {
              try {
                  cql = PartyUtil.getCQL(query,limit,offset,NOTIFY_TABLE);
              }catch (Exception e)
              {
                  logger.debug(e);
              }
          }

        PgUtil.postgresClient(vertxContext, okapiHeaders).get(NOTIFY_TABLE,org.folio.rest.jaxrs.model.ReserveGroup.class,
                new String[]{"*"}, cql,true,false,reply->{
                      if (reply.succeeded())
                      {
                          ReserveCollection reserveCollection = new ReserveCollection();
                          List<ReserveGroup> reserveGroup = reply.result().getResults();
                          Integer totalRecords = reply.result().getResultInfo().getTotalRecords();
                          reserveCollection.setReserveGroup(reserveGroup);
                          reserveCollection.setTotalRecords(totalRecords);
                          asyncResultHandler.handle(succeededFuture(GetPartyReserveResponse.respond200WithApplicationJson(reserveCollection)));
                      } else {
                          ValidationHelper.handleError(reply.cause(), asyncResultHandler);
                      }
                });

    }


    @Override
    public void putPartyReserveById(String id, String lang, org.folio.rest.jaxrs.model.Reserve entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
          PgUtil.put(NOTIFY_TABLE,entity,id,okapiHeaders,vertxContext,PutPartyReserveByIdResponse.class,asyncResultHandler);
        PartyLogSave.saveLog("审核活动名称为【"+ entity.getPartyName() +"】读者编号为【"+entity.getReaderReserveGroup().toString()+"】",3, entity.getMetadata(),entity.getOperator(),okapiHeaders,asyncResultHandler,PgUtil.postgresClient(vertxContext,okapiHeaders));
    }
}
